/*
 * @Description:获取项目相关区域
 * @Author: liyuhao
 * @Date: 2022-06-13 16:10:12
 * @LastEditors: liyuhao
 * @LastEditTime: 2022-06-13 16:10:19
 */
import {useCallback, useEffect, useState} from 'react'
import {getCurrentUser, getRegions, setRegions} from '@/utils/authority'
import {getRegionInfoTree} from "@/services/db/public.ts";
import {formatRegions} from "@/utils/format.ts";

/**
 * 只有登录后的页面才能使用此hook
 * 因为调用接口需要用到当前登录用户行政编码
 */
const useRegions: any = () => {
  const regions = getRegions();
  const [data, setData] = useState<any>(regions)
  const [nameMap, setNameMap] = useState<any>({})

  useEffect(() => {
    if (!regions) {
      const zoneCode = getCurrentUser().zoneCode
      const params = {zoneCode, depth: '-1'};
      getRegionInfoTree(params).then((res: any) => {
        setRegions(res);
        setData(formatRegions(res));
      })
    }
  }, [])

  const mapNameFunc = useCallback((regions: any[], nameMap: any) => {
    regions.forEach(item => {
      nameMap[item.value] = item.label;
      if (item.children?.length) {
        mapNameFunc(item.children, nameMap)
      }
    })
  }, [])

  useEffect(() => {
    const nameMap = {};
    if (data?.length) {
      mapNameFunc(data, nameMap)
    }
    setNameMap(nameMap);
  }, [data])

  const getName = useCallback((zoneCode: string) => nameMap[zoneCode], [nameMap])

  return [data, getName]
}

export default useRegions
